# 一些常见的方法

import datetime
import os
import hashlib
import random
import time
import io
from django.core.cache import cache
from django.http import HttpResponse,JsonResponse
from PIL import Image, ImageDraw, ImageFont
from .log import output_log
from config import ttf_path
from hashlib import sha256
from .settings import SECRET_KEY


## 生成验证码
def verify_code(request):
    """ 验证码 """
    code_id = request.GET.get("timestamp")
    if code_id is None:
        return JsonResponse({"status": 400, "msg": "未携带正确参数！"})
    bgcolor = (random.randrange(20, 100), random.randrange(20, 100), random.randrange(20, 100))
    width = 100
    height = 30
    # 字体间距
    spacing = width / 4
    # 字体大小
    fontSize = 20

    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)

    # 定义验证码的备选值
    strs = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += strs[random.randrange(0, len(strs))]
    # 构建字体对象
    font = ImageFont.truetype(ttf_path, size=fontSize)
    # 构造字体颜色
    fontcolor1 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor2 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor3 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor4 = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor1)
    draw.text((spacing, 2), rand_str[1], font=font, fill=fontcolor2)
    draw.text((spacing * 2, 2), rand_str[2], font=font, fill=fontcolor3)
    draw.text((spacing * 3, 2), rand_str[3], font=font, fill=fontcolor4)
    # 释放画笔
    del draw
    # 存入cache,用于做进一步验证
    cache.add(code_id, rand_str, timeout=180)
    # 内存文件操作
    buf = io.BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    res = HttpResponse(buf.getvalue(), 'image/png')
    output_log(f"code_id:{code_id}/code:{rand_str}", level="info")
    return res


## 生成token
def make_token(userid):
    text =SECRET_KEY + userid + str(random.randrange(10000, 99999))
    plainTextBytes = text.encode('utf-8')  # 字符串在哈希之前，需要编码
    encryptor = sha256()
    encryptor.update(plainTextBytes)
    hashCode = encryptor.hexdigest()
    return hashCode


## 判断文件类型
def get_file_cls(file_name):
    map = {
        1:[".txt",".docx",".doc"],
        2:[".csv",".xla",".xls",".xlsx"],
        3:[".ppt",".pptx"],
        4:[".jpeg",".jpg",".png",".webp"],
        5:[".avi",".mp4",".m4v",".mkv",".mp4v",".vm",".vmv"]
    }
    for k,v in map.items():
        for i in v:
            if file_name.endswith(i):
                return k
    return 6